import qs from 'qs'
import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken, getXsrftoken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;',
    'Accept': 'application/json'
  },
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (['post', 'put', 'delete'].includes(config.method)) {
      config.headers['X-Xsrftoken'] = getXsrftoken()
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    // console.log('request config.params ', typeof config.params, config.params, config.params != undefined || config.params != '')
    // console.log('request config.data ', typeof config.data, config.data)
    if (['post', 'put'].includes(config.method) && config.params && !config.data) {
      config.data = qs.stringify(config.params)
      config.params = {}
      // config.headers['Content-Length'] = config.data.length
    }
    // console.log('request config.params ', typeof config.params, config.params)
    // console.log('request config.data ', typeof config.data, config.data)
    // console.log('request use config ', config)
    return config
  },
  error => {
    // do something with request error
    console.log('interceptors.request error ', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // console.log('response data ', res)
    // if the custom code is not 0, it is judged as an error.
    if (res.code !== 0) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 706) {
        MessageBox.confirm(
          '你已被登出，可以取消继续留在该页面，或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('admin/logout').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else {
        console.log('response res: ', res)
        return Promise.reject(new Error(res.msg || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    console.log('request.js response error: ' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
